<template>  
  <div class="container">   
    <div class="main">  
      <div class="header">  
        <el-button type="primary" @click="add">新建</el-button>  
        <el-select v-model="selectedFilter" placeholder="请选择状态">  
          <el-option label="启用" value="1"></el-option>  
          <el-option label="禁用" value="0"></el-option>  
        </el-select>  
        <el-input placeholder="请输入关键字搜索" v-model="searchTable" />  
        <el-button type="info" @click="query">查询</el-button>  
        <el-button type="info" @click="cz">重置</el-button>  
      </div>  

      <el-table :data="tableData" border class="eltable">  
        <el-table-column prop="user_id" label="序号" width="80"></el-table-column>  
        <el-table-column prop="user_job_code" label="工号" ></el-table-column>  
        <el-table-column prop="user_uname" label="用户名" ></el-table-column>  
        <el-table-column prop="user_phone" label="手机号" ></el-table-column>  
        <el-table-column prop="user_email" label="邮箱" ></el-table-column>  
        <el-table-column prop="user_state" label="启用">
          <template #default="{ row }">
            <el-switch :model-value="row.user_state === 1" @click="onStatusChange(row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <el-space>
              <el-tooltip content="编辑" placement="top">
                <div class="operation-item" @click="editRow(row)">
                  <el-icon class="operation-icon">
                    <Edit />
                  </el-icon>
                  <span>编辑</span>
                </div>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <div class="operation-item" @click="deleteRow(row)">
                  <el-icon class="operation-icon delete">
                    <Delete />
                  </el-icon>
                  <span>删除</span>
                </div>
              </el-tooltip>
            </el-space>
          </template>
        </el-table-column> 
      </el-table>  
      <el-pagination  
        @current-change="handleCurrentChange"  
        :current-page="currentPage"  
        :page-size="pageSize"  
        :total="totalItems"  
        layout="total, prev, pager, next, jumper">  
      </el-pagination>  
    </div>  
  </div>  
  <el-dialog v-model="dialogVisible"
                title="添加"
                width="600"
                :before-close="handleClose">
        <span>
          <el-form :model="form" :inline="true" class="demo-form-inline">
            <el-row :gutter="20">
              <el-col :span="10">
                <el-form-item label="姓名" :label-width="formLabelWidth" >
                  <el-input v-model="form.name" autocomplete="off" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="用户名" :label-width="formLabelWidth" >
                  <el-input v-model="form.uname" autocomplete="off" clearable></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="10">
                <el-form-item label="邮箱" :label-width="formLabelWidth" >
                  <el-input v-model="form.email" autocomplete="off" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="手机号" :label-width="formLabelWidth" >
                  <el-input v-model="form.phone" autocomplete="off" clearable></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="10">
                <el-form-item label="密码" :label-width="formLabelWidth" >
                  <el-input v-model="form.pwd" autocomplete="off" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="角色" :label-width="formLabelWidth" >
                  <el-select 
                  v-model="form.rid" 
                  placeholder="角色" 
                  style="width: 200px"
                  @change="handleLeaderChange"
                >
                  <el-option
                    v-for="item in jstableData"
                    :key="item.role_id"
                    :label="item.role_name"
                    :value="item.role_id"
                  />
                </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addqr">确 定</el-button>
        </span>
    </el-dialog>
    <el-dialog v-model="xgdialogVisible"
                title="修改"
                width="600"
                :before-close="handleClose">
        <span>
          <el-form :model="xgform" :inline="true" class="demo-form-inline">
            <el-form-item label="姓名" :label-width="formLabelWidth" >
              <el-input v-model="xgform.name" autocomplete="off" clearable></el-input>
            </el-form-item>
            <el-form-item label="用户名" :label-width="formLabelWidth" >
              <el-input v-model="xgform.uname" autocomplete="off" clearable></el-input>
            </el-form-item>
            <el-form-item label="邮箱" :label-width="formLabelWidth" >
              <el-input v-model="xgform.email" autocomplete="off" clearable></el-input>
            </el-form-item>
            <el-form-item label="手机号" :label-width="formLabelWidth" >
              <el-input v-model="xgform.phone" autocomplete="off" clearable></el-input>
            </el-form-item>
            <el-form-item label="密码" :label-width="formLabelWidth" >
              <el-input v-model="xgform.pwd" autocomplete="off" clearable></el-input>
            </el-form-item>
            <el-form-item label="角色" :label-width="formLabelWidth" >
                  <el-select 
                  v-model="xgform.rid" 
                  placeholder="角色" 
                  style="width: 200px"
                  @change="handleLeaderChange"
                >
                  <el-option
                    v-for="item in jstableData"
                    :key="item.role_id"
                    :label="item.role_name"
                    :value="item.role_id"
                  />
                </el-select>
                </el-form-item>
          </el-form>
          <el-button @click="xgdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="xgqr">确 定</el-button>
        </span>
    </el-dialog>
</template>  

<script>  
import { ref, reactive, router,computed } from 'vue';  
import axios from 'axios'
import CryptoJS from 'crypto-js';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';

export default {  
  setup() {  
    const searchKey = ref('');  
    const treeData = ref([]);  
    const defaultProps = {  
      children: 'children',  
      label: 'label',  
    };  
    //加密方法
    function md5Encrypt(str) {
      return CryptoJS.MD5(str).toString();
    }
    //获取登录角色数据
    const uid=computed(()=>{
           return sessionStorage.getItem('u');
    })
    let yhid=reactive({
            id:uid
    })
    const tableData = ref([]);  
    const jstableData = ref([]);  

    const selectedFilter = ref('');  
    const searchTable = ref('');  
    const currentPage = ref(1);  
    const pageSize = ref(2);  
    const totalItems = ref(0);  
    let dialogVisible=ref(false);
    let xgdialogVisible=ref(false);
    let form=reactive({
          name:'',
          uname:'',
          phone:'',
          email:'',
          pwd:'',
          rid:'',
          uid:yhid.id
        })
    let xgform=reactive({
          id:'',
          name:'',
          uname:'',
          phone:'',
          email:'',
          pwd:'',
          rid:'',
          uid:yhid.id,
          user_code:''
    })
    const add = () => {  
      // 添加逻辑  
      dialogVisible.value=true;
    };  
    async function addqr(){
      const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1并补零
        const day = String(now.getDate()).padStart(2, '0'); // 补零
  
        // 生成四位随机数
        const randomNumber = Math.floor(1000 + Math.random() * 9000); // 生成1000到9999之间的随机数
  
        // 拼接时间字符串和随机数
        const formattedTime = `${year}${month}${day}`;
        let code=`yh${formattedTime}${randomNumber}`;
      try {
        const response =await axios.post('/api/User/PostUser',{
          user_job_code:code,
          user_uname:form.uname,
          user_name:form.name,
          user_phone:form.phone,
          user_email:form.email,
          user_pwd:md5Encrypt(form.pwd),
          // role_id:1,
          user_create_by:form.uid
        });
        if(response.data){
          const response =await axios.post('/api/Role/PostUser_Role?code='+code+'&id='+form.rid)
          if(response.data){
             ElMessage.error("添加成功");
            dialogVisible.value=false;
            SX();
          }
        }else{
           ElMessage.error("添加失败");
        }
      } catch (error) {
        console.error("请求错误:", error);
         ElMessage.error("服务器错误，请稍后重试。");
      }
        
    }
    async function SX () {  
      // 查询逻辑  
      try {
        const response = await axios.get('/api/User/GetFYUser?PageNumber='+currentPage.value+'&PageSize='+pageSize.value);
        const js = await axios.get('/api/Role/GetRole');
        jstableData.value=js.data
        tableData.value=response.data.user;
        totalItems.value=response.data.zon;
      } catch (error) {
        console.error("请求错误:", error);
         ElMessage.error("服务器错误，请稍后重试。");
      }
    };  
    SX();
    async function query () {  
      //查询逻辑  
      try {
        const response = await axios.get('/api/User/GetFYMHUser?PageNumber='+currentPage.value+'&PageSize='+pageSize.value+'&state='+selectedFilter.value+'&uname='+searchTable.value);
        tableData.value=response.data.user;
        totalItems.value=response.data.zon;
      } catch (error) {
        console.error("请求错误:", error);
         ElMessage.error("服务器错误，请稍后重试。");
      }
    };  
    const editRow = async(row) => {  
      xgdialogVisible.value=true;
      xgform.id=row.user_id;
      xgform.email=row.user_email;
      xgform.name=row.user_name;
      xgform.phone=row.user_phone;
      xgform.pwd=row.user_pwd;
      xgform.user_code=row.user_job_code
      // xgform.rid=row.role_id;
      xgform.uname=row.user_uname;
      try {
        const response = await axios.get('/api/Role/GetUser_Role?code='+row.user_job_code);
        xgform.rid=response.data
      } catch (error) {
        console.error("请求错误:", error);
         ElMessage.error("服务器错误，请稍后重试。");
      }
      console.log('Editing row:', row);  
    }; 
    //修改逻辑 
    async function xgqr(){
      try {
        const response =await axios.put('/api/User/UpdateUser',{
          user_id:xgform.id,
          user_uname:xgform.uname,
          user_name:xgform.name,
          user_phone:xgform.phone,
          user_email:xgform.email,
          user_pwd:md5Encrypt(xgform.pwd),
          // role_id:1,
          user_update_by:xgform.uid
        });
        if(response.data){
          const response =await axios.put('/api/Role/UpdateUser_Role?code='+xgform.user_code+'&id='+xgform.rid)
          if(response.data){
             ElMessage.error("修改成功");
            xgdialogVisible.value=false;
            SX();
          }
          
        }else{
           ElMessage.error("修改失败");
        }
      } catch (error) {
        console.error("请求错误:", error);
         ElMessage.error("服务器错误，请稍后重试。");
      }
    }
    //删除逻辑
    async function deleteRow(row){  
      try {
        if (confirm("确定要删除吗？")) {
          const response =await axios.delete('/api/User/DeleteUser?id='+row.user_id);
          if(response.data){
             ElMessage.error("删除成功");
            dialogVisible.value=false;
            SX();
          }else{
             ElMessage.error("删除失败");
          }
        }
      } catch (error) {
        console.error("请求错误:", error);
         ElMessage.error("服务器错误，请稍后重试。");
      } 
    };  

    const handleCurrentChange = (page) => {  
      currentPage.value = page;  
      // 分页逻辑  
      SX();
    };  
    //修改状态
    const onStatusChange = async (row) => {
      const updatedStatus = row.user_state === 1 ? 0 : 1;
      try {
        await axios.put('/api/User/UpdateUserZT?code='+row.user_job_code+'&state='+updatedStatus);
        row.user_state = updatedStatus; // 更新本地状态  
        ElMessage.success('状态更新成功');
      } catch (error) {
        console.error('状态更新失败:', error);
        ElMessage.error('状态更新失败');
      }
    };
    function cz(){
      selectedFilter.value=''
      searchTable.value=''
      SX()
    }
    // 确保所有函数都被返回  
    return {  
      searchKey,  
      treeData,  
      defaultProps,  
      tableData,  
      selectedFilter,  
      searchTable,  
      currentPage,  
      pageSize,  
      totalItems,  
      add,  
      query,  
      editRow,  
      deleteRow,  
      handleCurrentChange, 
      dialogVisible ,
      form,
      addqr,
      xgform,
      xgdialogVisible,
      xgqr,
      onStatusChange,
      cz,
      jstableData
    };  
  },  
  methods: {
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      }
    }
};  
</script>  

<style>  
.container {  
  display: flex;  
  gap: 20px;
  height: 95%;
}  

.sidebar {  
  height: 100%;
  
}  

.main {  
  width: 80%;
  flex: 1;  
  height: 100%;
}  

.header {  
   display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}  
.eltable{
  height: 95%;
}
.letree{
  height: 100%;
}
.demo-form-inline .el-input {
  --el-input-width: 200px;
}

.demo-form-inline .el-select {
  --el-select-width: 200px;
}
</style>